package cn.steam.foo.config;

import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadPoolExecutor;

import static cn.steam.foo.filter.TraceIdFilter.TRACE_ID;

@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {

    private static final int corePoolSize = 50;            // 核心线程数（默认线程数）
    private static final int maxPoolSize = 100;                // 最大线程数
    private static final int keepAliveTime = 10;            // 允许线程空闲时间（单位：默认为秒）
    private static final int queueCapacity = Integer.MAX_VALUE;          // 缓冲队列数
    private static final String threadNamePrefix = "Foo-Async-"; // 线程池名前缀

    @Bean("taskExecutor") // bean的名称，默认为首字母小写的方法名
    @Primary
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setTaskDecorator(new MdcTaskDecorator());

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }

    private static class MdcTaskDecorator implements TaskDecorator {
        @Override
        public Runnable decorate(Runnable runnable) {
            Map<String, String> map = MDC.getCopyOfContextMap();
            return () -> {
                try {
                    MDC.setContextMap(map);
                    String traceId = MDC.get(TRACE_ID);
                    if (StringUtils.isEmpty(traceId)) {
                        traceId = UUID.randomUUID().toString();
                        MDC.put(TRACE_ID, traceId);
                    }
                    runnable.run();
                } finally {
                    MDC.clear();
                }
            };
        }
    }

}
